package yu.zhou.njupt.importdataui.core;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;

import yu.zhou.njupt.importdataui.entity.Column;
import yu.zhou.njupt.importdataui.entity.ImportResult;

public class Importer {
    
    public Connection conn = null;
    int batch_num;
    
    public Importer(Connection conn) throws Exception {
        this.conn = conn;
    }

    /** 将数据从数据源中导入到数据库(核心方法) */
    public ImportResult importData(File sourceFile) {
        return null;
    };
    
    protected void doBeofreImport(String tableName, List<Column> columnList) throws Exception {
        Statement s = conn.createStatement();
        int num = -1;
        
        ResultSet rs = s.executeQuery("select count(1) from user_tables where table_name = '" + tableName.toUpperCase() + "'");
        
        if (rs.next()) {
            num = rs.getInt(1);
        }
        if (num == 1) {
            System.out.println("表" + tableName.toUpperCase() + "已存在");
        } else {
            String sql = "create table " + tableName + "(";
            for (Column column : columnList) {
                sql += column.getName() + " " + column.getType() + ",";
            }
            sql = sql.substring(0, sql.length() - 1) + ")";
            s.execute(sql);
            System.out.println("表" + tableName.toUpperCase() + "创建成功");
        }
        
        DbUtils.closeQuietly(s);
    }
    
    /** 向一张表导入数据后所需做的操作 */
    protected void doAfterImport(String tableName, String filename, String sheetName) throws Exception {
        /* 更新日志表(z_table) */
//        String sql = SqlUtil.getSqlForUpdateLog();
//        sql = MessageFormat.format(sql,   
//                "'" + tableName.toUpperCase() + "'", 
//                "'" + filename.toLowerCase() + "-" + (sheetName == null ? "" : sheetName.toLowerCase()) + "'",
//                batch_num);
//                
//        PreparedStatement ps = conn.prepareStatement(sql);
//        ps.setString(1, tableName);
//        ps.executeUpdate();
//
//        DbUtils.closeQuietly(ps);
    }
    
}